﻿using EasyNetQ;
using EasyNetQTest.AspnetCore.Config;
using EasyNetQTest.AspnetCore.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EasyNetQTest.AspnetCore.Services
{
    public class MQSendService
    {
        IBus bus;

        public MQSendService(IBus bus)
        {
            this.bus = bus;
        }

        /// <summary>
        /// 发送消息,异步发送，不等待发送完成
        /// </summary>
        public async Task SendMessageNoWaitAsync(int sendCount =1)
        {
            //异步发送，不等待发送完成
            DoWorkAsync(sendCount);
        }

        /// <summary>
        /// 发送消息,异步发送，等待发送完成
        /// </summary>
        public async Task SendMessageWaitAsync(int sendCount = 1)
        {
            //异步发送，等待发送完成
            await DoWorkAsync(sendCount);
        }

        /// <summary>
        /// 具体发送逻辑
        /// </summary>
        /// <param name="sendCount"></param>
        /// <returns></returns>
        private async Task DoWorkAsync(int sendCount)
        {
            string msg = "发送的消息";
            //异步发送，不等待
            await Task.Run(() => {
                for (int i = 0; i < sendCount; i++)
                {
                    var message = msg + i;
                    var msgModel = new MQMessage
                    {
                        MsgId = i,
                        MsgType = "MsgType1",
                        MsgContent = message
                    };

                    //发送消息,直接异步发送，不等待
                    bus.SendAsync<MQMessage>(Consts.QueueName, msgModel);

                    //Console.WriteLine("发送消息:\"{0}\" 成功", message);
                }
            });
        }
    }
}
